package com.ds.iot.comet;

import com.ds.client.JDSSessionFactory;
import com.ds.common.JDSConstants;
import com.ds.common.JDSException;
import com.ds.common.logging.Log;
import com.ds.common.logging.LogFactory;
import com.ds.context.JDSContext;
import com.ds.engine.ConnectionHandle;
import com.ds.server.JDSClientService;
import com.ds.server.JDSServer;
import com.ds.server.eumus.ConfigCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JDSCometServer extends HttpServlet {

    public static final String SESSIONID = "sessionId";

    public static final String HEARTKEY = "0";

    static JDSCometServer instance;

    public static final String THREAD_LOCK = "Thread Lock";

    private static Map<String, Integer> checkBlack = new HashMap<String, Integer>();

    private static Map<String, Long> checkBlackTime = new HashMap<String, Long>();

    private static final Log logger = LogFactory.getLog(JDSConstants.CONFIG_KEY, JDSCometServer.class);

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            CometActionContextImpl context = new CometActionContextImpl(req, resp);
            String ieee = (String) context.getParams("ieee");
            if (ieee != null) {
                Integer times = checkBlack.get(ieee);
                if (times == null) {
                    times = 1;

                } else {
                    times++;
                }

                if (times > 300000) {
                    Long lastCheckTime = checkBlackTime.get(ieee);
                    if (lastCheckTime == null) {
                        lastCheckTime = System.currentTimeMillis();
                        checkBlackTime.put(ieee, lastCheckTime);
                    }
                    if (System.currentTimeMillis() - lastCheckTime < 60 * 60 * 1000) {
                        resp.getWriter().println(
                                "ieee =[" + ieee + "] login times>30 url:[" + req.getRequestURL() + "] place login again after 1 hours!");
                        resp.getWriter().flush();
                        resp.flushBuffer();
                    } else {
                        checkBlackTime.put(ieee, System.currentTimeMillis());
                        times = 0;
                    }
                } else {
                    checkBlackTime.put(ieee, System.currentTimeMillis());
                }

                checkBlack.put(ieee, times);
            }

            JDSClientService client = this.getClient(context);

            String sessionId = (String) context.getSessionId();
            if (sessionId != null) {
                if (client != null) {
                    ConnectionHandle handle = client.getConnectionHandle();
                    // client.setContext(context);
                    handle.connect(context);
                } else {

                    String body = "sessionId is invalidate sessionId=[" + sessionId + "]  url:[" + req.getRequestURL() + "] place login again!";
                    logger.info(body);
                    resp.getWriter().println(body);
                    resp.getWriter().flush();
                    resp.flushBuffer();
                }
            } else {

                String body = "sessionId is  null,  place login frist!";
                logger.info(body);
                resp.getWriter().println(body);
                resp.getWriter().flush();
                resp.flushBuffer();
            }

        } catch (JDSException e1) {
            e1.printStackTrace();
            logger.error(e1);
            resp.getWriter().println("sessionId is invalidate  url:[" + req.getRequestURL() + "] place login again!");
            resp.getWriter().flush();
            resp.flushBuffer();

        }

    }

    public JDSClientService getClient(JDSContext context) throws JDSException {

        JDSSessionFactory factory = new JDSSessionFactory(context);
        String sessionId = (String) context.getSessionId();

        if (sessionId == null) {
            sessionId = (String) context.getParams(context.JSESSIONID);
        }
        if (sessionId != null) {
            context.getContext().put(context.JSESSIONID, sessionId);
        }
        String systemCode = JDSServer.getInstance().getCurrServerBean().getId();

        context.getContext().put(context.SYSCODE, systemCode);

        JDSClientService appClient = null;
        try {
            appClient = factory.getJDSClientBySessionId(sessionId, ConfigCode.gw);
        } catch (JDSException e) {
            logger.error("sessionId is invalidate sessionId=[" + sessionId + "] ieee=[" + context.getParams("ieee") + "] place login again!");
            // e.printStackTrace();
        }

        if (appClient != null) {
            appClient.setContext(context);
        }

        return appClient;
    }

}
